<!-- 按钮控制舵机 -->

<div id="engines">
    <div id="engine0" class="engine" data-engine-id="0">
        <button class="sub">-</button>
        0号:<span class="pwm">1500</span>
        <button class="add">+</button>
    </div>
    <div id="engine1" class="engine" data-engine-id="1">
        <button class="sub">-</button>
        1号:<span class="pwm">1500</span>
        <button class="add">+</button>
    </div>
    <div id="engine2" class="engine" data-engine-id="2">
        <button class="sub">-</button>
        2号:<span class="pwm">1500</span>
        <button class="add">+</button>
    </div>
    <div id="engine3" class="engine" data-engine-id="3">
        <button class="sub">-</button>
        3号:<span class="pwm">1500</span>
        <button class="add">+</button>
    </div>
    <div id="engine4" class="engine" data-engine-id="4">
        <button class="sub">-</button>
        4号:<span class="pwm">1500</span>
        <button class="add">+</button>
    </div>
    <div id="engine5" class="engine" data-engine-id="5">
        <button class="sub">-</button>
        5号:<span class="pwm">1500</span>
        <button class="add">+</button>
    </div>
</div>


<script>
    $(document).ready(function () {
        // 事件委托，监听所有 .engine 容器内的按钮点击事件
        $('.engine').on('click', '.sub, .add', function () {

            var $engine = $(this).closest('.engine');// 获取点击的按钮所在的计数器容器
            var engineId = $engine.data('engine-id');
            var $pwm = $engine.find('.pwm');// 获取计数器显示的元素
            var currentValue = parseInt($pwm.text(), 10);// 获取当前计数值

            // 判断是增加按钮还是减少按钮
            if ($(this).hasClass('add')) {
                currentValue += 100;
            } else if ($(this).hasClass('sub')) {
                currentValue -= 100;
            }

            // update
            fetch('/engine', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: engineId,
                    pwm: currentValue
                })
            }).then(response => response.json()).then(data => {
                printc(data)
            })
            $pwm.text(currentValue);
        });
    });
</script>
